/*******************************************************************************
 * Package: com.song.boot.springstudy.ms.szjz
 * Type:    PriceFetcherV2
 * Date:    2025/8/8 11:11
 *
 * Copyright (c) 2025 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.ms.szjz.al5;

import lombok.Data;
import lombok.SneakyThrows;
import lombok.ToString;
import org.apache.commons.lang3.time.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2025/8/8 11:11
 */
public class PriceFetcherV3 {
    // 把任务放到队列当中
    private static LinkedBlockingQueue<Runnable> wordQueue = new LinkedBlockingQueue<>();
    // 创建单线程池来处理请求，保证顺序执行
    private static ExecutorService processor = Executors.newSingleThreadExecutor();

    public PriceFetcherV3() {
        this.runTask();
    }

    // 存任务
    @SneakyThrows
    private static void putTask(Runnable run) {
        wordQueue.put(run);
    }

    // 执行任务
    private static void runTask() {
        processor.execute(()->{
            Runnable run = null;
            try {
                run = wordQueue.take();
                // 记录开始时间
                long startTime = System.currentTimeMillis();
                run.run();
                // 记录结束时间
                long endTime = System.currentTimeMillis();


            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }

    // 关闭线程池
    public static void shutdown_01() {
        processor.shutdown();
    }


    @SneakyThrows
    public static void main(String[] args) {
        StopWatch stopWatch = StopWatch.createStarted();

        // 5s=5000ms
        long msAll= 5000;
        // 处理数据的和
        AtomicLong msSum = new AtomicLong();

        // 初始化 10个参数
        List<PackData> datas = new ArrayList<>();

        for (int i = 0, size = 10; i < size; i++) {

            PriceFetcherV3 v3 = new PriceFetcherV3();
            int finalI = i;
            v3. putTask(()->{
                callThirdPartyAPI(finalI);
            });

        }

        shutdown_01();

        System.out.println(datas);
        // 5 秒内返回数据。不管是否执行完成 把 5 秒内的能做响应的数据返回
        // CompletableFuture.allOf().get(5, TimeUnit.SECONDS);

        // 停止计时器
        stopWatch.stop();
        // 输出执行时间
        System.out.println("代码执行时间：" + stopWatch.getTime() + " 毫秒");
    }

    // PackData packData = new PackData();
    // // 记录开始时间
    // long startTime = System.currentTimeMillis();
    // Double data = callThirdPartyAPI(finalI);
    // // 记录结束时间
    // long endTime = System.currentTimeMillis();
    //             packData.setData(data);
    //             packData.setIndex(finalI);
    //             packData.setMs(endTime - startTime);
    //             datas.add(packData);
    //             msSum.addAndGet(packData.getMs());
    // // 小于5s 直接返回
    //         if (msSum.get() <= msAll) {
    //
    // }else {
    //     // 大于5s 返回5秒内查询的数据
    //     break;
    // }



    // 模拟第三方API调用 每秒处理5个请求   串行
    @SneakyThrows
    private static Double callThirdPartyAPI(int i)  {
        //
        // 模拟网络延迟 (100ms ~ 1000ms)
        int delay = 100 + (int)(Math.random() * 900);
        Thread.sleep(delay);

        System.out.println("---------------"+i);
        // 生成随机价格作为模拟结果
        return Double.parseDouble(String.format("%.2f", Math.random() * 100));
    }







    @Data
    @ToString
    static class PackData {
        private int index;
        private double data;
        private long ms;
    }
}
